package com.keldian.myqq.net;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;

import com.google.gson.Gson;
import com.keldian.myqq.R;
import com.keldian.myqq.adapter.MyNewsAdapter;
import com.keldian.myqq.entity.UserInfoWrapper;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


/**
 * Created by Administrator on 15-11-17.
 */
public class HttpGetData extends AsyncTask<String, Void, String> {
    private URL url;
    private HttpURLConnection connection;
    private ListView listView;
    private Context context;

    public HttpGetData(ListView listView, Context context) {
        this.listView = listView;
        this.context = context;
    }

    @Override
    protected String doInBackground(String... params) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader bufferedReader = null;

        try {
            url = new URL("http://192.168.0.166:8080/users/userinfos.xml");
            connection = (HttpURLConnection) url.openConnection();
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return sb.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.i("Tag", result);
        try{
            Gson gson = new Gson();
            UserInfoWrapper wrapper =  new Gson().fromJson(result, UserInfoWrapper.class);
            MyNewsAdapter adapter = new MyNewsAdapter(context, wrapper.userInfo);
            listView.setAdapter(adapter);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
